package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService{

    //关联mapper
    @Autowired
    private UserMapper userMapper;

    @Override
    public void saveOrUpdate(User user) {
        //id为空,新增操作
        if(user.getId()==null){
            //判断数据库中是否已经存在此邮箱,因为登录校验需要同时查账户密码,索性就设计两个参数的方法,
            User temp=userMapper.selectByEmailAndPassword(user.getEmail(),null);
            if(temp!=null){
                throw new RuntimeException("该邮箱已被注册!");
            }
            //自动设置默认头像,默认背景图片
            user.setCoverImgUrl("/img/user/bg.jpeg");
            user.setHeadImgUrl("/img/user/head.jpg");
            userMapper.insert(user);
        }else{
            userMapper.updateByPrimaryKey(user);
        }


    }

    @Override
    public User login(String email, String password) {
        User user = userMapper.selectByEmailAndPassword(email, password);
        if(user==null){
            throw new RuntimeException("账号密码不匹配");
        }
        return user;
    }

    @Override
    public PageInfo<User> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<User> list = userMapper.selectForList(qo);
        return new PageInfo<User>(list);
    }

    @Override
    public User queryById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<User> queryAll() {
        return userMapper.selectAll();
    }
}
